package com.linghang.back.exception;

import com.linghang.back.dto.ApiResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.QueryTimeoutException;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import jakarta.validation.ConstraintViolationException;
import java.util.List;
import java.util.stream.Collectors;

@RestControllerAdvice
public class GlobalExceptionHandler {
    
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    
    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.OK)
    public ApiResponse<Void> handleBusinessException(BusinessException e) {
        logger.warn("业务异常: {}", e.getMessage());
        return ApiResponse.fail(e.getCode(), e.getMessage());
    }
    
    /**
     * 处理Redis连接超时异常
     */
    @ExceptionHandler(QueryTimeoutException.class)
    @ResponseStatus(HttpStatus.OK)
    public ApiResponse<Void> handleRedisTimeoutException(QueryTimeoutException e) {
        logger.error("Redis连接超时: {}", e.getMessage(), e);
        return ApiResponse.fail(500, "操作超时，请稍后再试");
    }
    
    /**
     * 处理Redis连接失败异常
     */
    @ExceptionHandler(RedisConnectionFailureException.class)
    @ResponseStatus(HttpStatus.OK)
    public ApiResponse<Void> handleRedisConnectionFailureException(RedisConnectionFailureException e) {
        logger.error("Redis连接失败: {}", e.getMessage(), e);
        return ApiResponse.fail(500, "系统繁忙，请稍后再试");
    }
    
    /**
     * 处理数据访问异常
     */
    @ExceptionHandler(DataAccessException.class)
    @ResponseStatus(HttpStatus.OK)
    public ApiResponse<Void> handleDataAccessException(DataAccessException e) {
        logger.error("数据访问异常: {}", e.getMessage(), e);
        return ApiResponse.fail(500, "数据访问异常，请稍后再试");
    }
    
    /**
     * 处理参数校验异常 (@Valid注解)
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.OK)
    public ApiResponse<Void> handleValidationException(MethodArgumentNotValidException e) {
        List<String> errors = e.getBindingResult().getFieldErrors()
                .stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.toList());
        String errorMessage = String.join("; ", errors);
        logger.warn("参数校验失败: {}", errorMessage);
        return ApiResponse.fail(400, errorMessage);
    }
    
    /**
     * 处理参数绑定异常
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.OK)
    public ApiResponse<Void> handleBindException(BindException e) {
        List<String> errors = e.getBindingResult().getFieldErrors()
                .stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.toList());
        String errorMessage = String.join("; ", errors);
        logger.warn("参数绑定失败: {}", errorMessage);
        return ApiResponse.fail(400, errorMessage);
    }
    
    /**
     * 处理约束违反异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.OK)
    public ApiResponse<Void> handleConstraintViolationException(ConstraintViolationException e) {
        logger.warn("约束违反: {}", e.getMessage());
        return ApiResponse.fail(400, e.getMessage());
    }
    
    /**
     * 处理所有其他未处理的异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    public ApiResponse<Void> handleException(Exception e) {
        logger.error("系统错误", e);
        return ApiResponse.fail(500, "系统错误，请联系管理员");
    }
} 